//
//  UIView+HUD.m
//  WXReader
//
//  Created by LL on 2021/9/27.
//  Copyright © 2021 Andrew. All rights reserved.
//

#import "UIView+HUD.h"

@implementation UIView (HUD)

#pragma mark - Loading样式的HUD

/// 弹出一个背景透明带文字的菊花HUD，当title为nil不显示文字
- (MBProgressHUD *)showClearHUDFromText:(nullable NSString *)title {
    return [self showHUDFromText:title isTranslucent:NO graceTime:kHUDGraceTime];
}

/// 立即弹出一个背景透明带文字的菊花HUD，当title为nil不显示文字
- (MBProgressHUD *)promptShowClearHUDFromText:(nullable NSString *)title {
    return [self showHUDFromText:title isTranslucent:NO graceTime:0.0];
}

- (MBProgressHUD *)showDarkHUDFromText:(nullable NSString *)title {
    return [self showHUDFromText:title isTranslucent:YES graceTime:kHUDGraceTime];
}

- (MBProgressHUD *)promptShowDarkHUDFromText:(nullable NSString *)title {
    return [self showHUDFromText:title isTranslucent:YES graceTime:0.0];
}

- (MBProgressHUD *)showHUDFromText:(NSString *)title isTranslucent:(BOOL)isTranslucent graceTime:(NSTimeInterval)graceTime {
    /// 防止弹出多个信息一样的HUD
    static NSMutableSet<NSString *> *_titleSets = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _titleSets = [NSMutableSet set];
    });
    if (title != nil) {
        if ([_titleSets containsObject:title]) return nil;
        [_titleSets addObject:title];
    }
    
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self];
    hud.contentColor = UIColor.whiteColor;
    hud.margin = 30;
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    hud.bezelView.backgroundColor = kBlackColor;
    [UIActivityIndicatorView appearanceWhenContainedInInstancesOfClasses:@[[MBProgressHUD class]]].color = UIColor.whiteColor;
    hud.graceTime = graceTime;
    hud.minShowTime = kHUDMinShowTime;
    hud.userInteractionEnabled = YES;
    hud.label.numberOfLines = 2;
    hud.label.text = title;
    if (isTranslucent) {
        hud.backgroundColor = RGBA(0, 0, 0, 0.5);
    }
    
    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeSystem];
    closeButton.hidden = YES;
    [closeButton setImage:[[UIImage imageNamed:@"public_close"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    closeButton.tintColor = UIColor.whiteColor;
    [closeButton setImageEdgeInsets:UIEdgeInsetsMake(5, 33, 33, 5)];
    __weak typeof(hud) weakHUD = hud;
    [closeButton addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
//        !weakHUD.closeBlock ?: weakHUD.closeBlock();
        [weakHUD hideAnimated:YES];
    }]];
    [hud.bezelView addSubview:closeButton];
    [closeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(hud.bezelView);
        make.right.equalTo(hud.bezelView);
        make.width.height.mas_equalTo(50.0);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kHUDMinCloseTime * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        closeButton.hidden = NO;
    });
        
    hud.completionBlock = ^{
        if (title == nil) return;
        [_titleSets removeObject:title];
    };
    
    [self addSubview:hud];
    [hud showAnimated:YES];
    
    return hud;
}


#pragma mark - 文字样式的HUD
/// 根据Error.code弹出一个Error样式的文字HUD
- (nullable MBProgressHUD *)showErrorHUDFromError:(NSError *)error {
    NSString *message = WXLocalizedString(@"失败");
    return [self showErrorHUDFromText:message];
}

/// 弹出一个Error样式的文字HUD
- (nullable MBProgressHUD *)showErrorHUDFromText:(NSString *)text {
    return [self showTextHUD:text afterDelay:kHUDDuration];
}

/// 弹出一个Success样式的文字HUD
- (nullable MBProgressHUD *)showSuccessHUDFromText:(NSString *)text {
    return [self showTextHUD:text afterDelay:kHUDDuration];
}

/// 弹出一个普通样式的文字HUD
- (MBProgressHUD *)showNormalHUDFromText:(NSString *)text {
    return [self showTextHUD:text afterDelay:kHUDDuration];
}

- (nullable MBProgressHUD *)showTextHUD:(NSString *)text afterDelay:(NSTimeInterval)afterDelay {
    if (![text isKindOfClass:NSString.class]) return nil;
    if (text.length == 0) return nil;
    
    
    /// 防止弹出多个信息一样的HUD
    static NSMutableSet<NSString *> *_titleSets = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _titleSets = [NSMutableSet set];
    });
    if ([_titleSets containsObject:text]) return nil;
    [_titleSets addObject:text];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self animated:YES];
    hud.completionBlock = ^{
        [_titleSets removeObject:text];
    };
    hud.userInteractionEnabled = NO;
    hud.mode = MBProgressHUDModeText;
    
    // 使用 detailsLabel 并配置多行
    hud.detailsLabel.text = text;
    hud.detailsLabel.numberOfLines = 0;
    hud.detailsLabel.font = [UIFont systemFontOfSize:14]; // 可选：调整字体大小
    CGFloat maxWidth = CGRectGetWidth(self.bounds) - 40;
    hud.detailsLabel.preferredMaxLayoutWidth = maxWidth;
    
    // 调整 HUD 布局
    hud.margin = 12.0;
    hud.minSize = CGSizeMake(120, 40); // 确保最小高度
    hud.offset = CGPointMake(0, 0); // 居中显示
    
    [hud hideAnimated:YES afterDelay:afterDelay];
    return hud;
}

@end
